package Rangel.firebrigade.util;

import adf.agent.info.ScenarioInfo;
import adf.agent.info.WorldInfo;
import Rangel.common.world.helper.RangelWorldHelper;
import Rangel.common.world.entity.RangelBuilding;
import rescuecore2.standard.entities.*;
import rescuecore2.worldmodel.EntityID;

import java.util.*;
import java.util.List;

public class FireBrigadeUtilities {
    private static final int EXTINGUISH_DISTANCE_THRESHOLD = 5000;


    public static int waterNeededToExtinguish(RangelBuilding building) {
        return WaterCoolingEstimator.getWaterNeeded(building.getSelfBuilding().getGroundArea(), building.getSelfBuilding().getFloors(),
                building.getSelfBuilding().getBuildingCode(), building.getEstimatedTemperature(), 20);
    }

    public static int waterNeededToExtinguishNotEstimated(Building building) {
        return WaterCoolingEstimator.getWaterNeeded(building.getGroundArea(), building.getFloors(),
                building.getBuildingCode(), building.getTemperature(), 20);
    }

    public static int calculateWaterPower(int remainedWater, int maxPower, RangelBuilding building) {
        return Math.min(remainedWater, Math.min(maxPower, Math.max(500, waterNeededToExtinguish(building))));
    }

    public static int calculateWaterPowerNotEstimated(int remainedWater, int maxPower, Building building) {
        return Math.min(remainedWater, Math.min(maxPower, Math.max(500, waterNeededToExtinguishNotEstimated(building))));
    }

    public static Set<EntityID> findAreaIDsInExtinguishRange(WorldInfo worldInfo, ScenarioInfo scenarioInfo, EntityID source) {
        Set<EntityID> result = new HashSet<>();
        int maxExtinguishDistance = scenarioInfo.getFireExtinguishMaxDistance() - EXTINGUISH_DISTANCE_THRESHOLD;
        for (StandardEntity next : worldInfo.getObjectsInRange(source, (int) (maxExtinguishDistance * 1.5))) {
            if (next instanceof Area && worldInfo.getDistance(next.getID(), source) < maxExtinguishDistance) {
                result.add(next.getID());
            }
        }
        return result;
    }

    public static List<RangelBuilding> findBuildingsInExtinguishRangeOf(RangelWorldHelper worldHelper, WorldInfo worldInfo,ScenarioInfo scenarioInfo, EntityID source) {
        List<RangelBuilding> result = new ArrayList<>();
        int maxExtinguishDistance = scenarioInfo.getFireExtinguishMaxDistance()- EXTINGUISH_DISTANCE_THRESHOLD;
        for (StandardEntity next : worldInfo.getObjectsInRange(source, (int) (maxExtinguishDistance * 1.5))) {
            if (next instanceof Building) {
                RangelBuilding building = worldHelper.getRangelBuilding(next.getID());
                if (worldInfo.getDistance(next.getID(), source) < maxExtinguishDistance) {
                    result.add(building);
                }
            }
        }
        return result;
    }
}
